<template>
  <view class="data-insights-container">
    <!-- 渐变背景头部 -->
    <view class="header-gradient">
      <view class="header-content">
        <text class="back-btn" @click="goBack">←</text>
        <text class="header-title">数据洞察</text>
        <text class="header-subtitle">Data Insights</text>
      </view>
    </view>

    <!-- 时间选择器 -->
    <view class="time-selector">
      <view class="time-card">
        <view class="time-options">
          <view 
            class="time-option" 
            :class="{ active: timeRange === 'today' }" 
            @click="changeTimeRange('today')"
          >
            <text>今日</text>
          </view>
          <view 
            class="time-option" 
            :class="{ active: timeRange === 'week' }" 
            @click="changeTimeRange('week')"
          >
            <text>本周</text>
          </view>
          <view 
            class="time-option" 
            :class="{ active: timeRange === 'month' }" 
            @click="changeTimeRange('month')"
          >
            <text>本月</text>
          </view>
          <view 
            class="time-option" 
            :class="{ active: timeRange === 'custom' }" 
            @click="showDatePicker = true"
          >
            <text>自定义</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 核心指标卡片 -->
    <view class="metrics-section">
      <view class="metrics-grid">
        <view class="metric-card">
          <view class="metric-icon">📥</view>
          <view class="metric-content">
            <text class="metric-value">{{ formatNumber(totalInbound) }}</text>
            <text class="metric-label">入库总量(吨)</text>
            <text class="metric-trend" :class="getTrendClass(inboundTrend)">
              {{ inboundTrend > 0 ? '↑' : '↓' }} {{ Math.abs(inboundTrend) }}%
            </text>
          </view>
        </view>
        
        <view class="metric-card">
          <view class="metric-icon">📤</view>
          <view class="metric-content">
            <text class="metric-value">{{ formatNumber(totalOutbound) }}</text>
            <text class="metric-label">出库总量(吨)</text>
            <text class="metric-trend" :class="getTrendClass(outboundTrend)">
              {{ outboundTrend > 0 ? '↑' : '↓' }} {{ Math.abs(outboundTrend) }}%
            </text>
          </view>
        </view>
        
        <view class="metric-card">
          <view class="metric-icon">⚖️</view>
          <view class="metric-content">
            <text class="metric-value">{{ formatNumber(currentStock) }}</text>
            <text class="metric-label">当前库存(吨)</text>
            <text class="metric-status" :class="getStockStatusClass(currentStock)">
              {{ getStockStatusText(currentStock) }}
            </text>
          </view>
        </view>
        
        <view class="metric-card">
          <view class="metric-icon">🔄</view>
          <view class="metric-content">
            <text class="metric-value">{{ turnoverRate }}</text>
            <text class="metric-label">周转率</text>
            <text class="metric-desc">次/月</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 图表区域 -->
    <view class="charts-section">
      <!-- 库存趋势图 -->
      <view class="chart-card">
        <view class="chart-header">
          <text class="chart-title">库存趋势</text>
          <view class="chart-legend">
            <view class="legend-item">
              <view class="legend-color" style="background: #84fab0;"></view>
              <text>入库</text>
            </view>
            <view class="legend-item">
              <view class="legend-color" style="background: #fa709a;"></view>
              <text>出库</text>
            </view>
          </view>
        </view>
        <view class="chart-container">
          <canvas canvas-id="stockTrendChart" class="chart-canvas"></canvas>
        </view>
      </view>

      <!-- 物料权重分析 -->
      <view class="chart-card">
        <view class="chart-header">
          <text class="chart-title">权重物料TOP5</text>
          <text class="chart-subtitle">按库存占比排序</text>
        </view>
        <view class="material-list">
          <view 
            class="material-item" 
            v-for="(item, index) in topMaterials" 
            :key="index"
          >
            <view class="material-info">
              <text class="material-name">{{ item.name }}</text>
              <text class="material-spec">{{ item.spec }}</text>
            </view>
            <view class="material-bar">
              <view 
                class="progress-fill" 
                :style="{ width: item.percentage + '%', background: item.color }"
              ></view>
              <text class="percentage">{{ item.percentage }}%</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 库存分布饼图 -->
      <view class="chart-card">
        <view class="chart-header">
          <text class="chart-title">库存分布</text>
          <text class="chart-subtitle">按物料类型</text>
        </view>
        <view class="chart-container">
          <canvas canvas-id="stockDistributionChart" class="chart-canvas"></canvas>
        </view>
      </view>
    </view>

    <!-- 红冲功能模块 -->
    <view class="red-charge-section">
      <view class="section-title">异常处理</view>
      <view class="red-charge-grid">
        <view class="red-charge-card" @click="openInboundRedCharge">
          <view class="card-icon">🔴</view>
          <view class="card-content">
            <text class="card-title">入库红冲</text>
            <text class="card-desc">扫码撤销入库记录</text>
          </view>
          <text class="card-arrow">→</text>
        </view>
        
        <view class="red-charge-card" @click="openOutboundRedCharge">
          <view class="card-icon">🔴</view>
          <view class="card-content">
            <text class="card-title">出库红冲</text>
            <text class="card-desc">扫码撤销出库记录</text>
          </view>
          <text class="card-arrow">→</text>
        </view>
      </view>
    </view>

    <!-- 操作记录 -->
    <view class="operation-records">
      <view class="section-title">最近操作</view>
      <view class="record-list">
        <view 
          class="record-item" 
          v-for="(record, index) in recentRecords" 
          :key="index"
        >
          <view class="record-icon" :class="getRecordIconClass(record.type)">
            {{ getRecordIcon(record.type) }}
          </view>
          <view class="record-content">
            <text class="record-title">{{ record.title }}</text>
            <text class="record-time">{{ record.time }}</text>
          </view>
          <view class="record-amount" :class="getAmountClass(record.amount)">
            {{ record.amount > 0 ? '+' : '' }}{{ record.amount }}吨
          </view>
        </view>
      </view>
    </view>

    <!-- 红冲扫码弹窗 -->
    <u-popup 
      :show="showRedChargePopup" 
      mode="bottom" 
      @close="closeRedChargePopup"
    >
      <view class="red-charge-popup">
        <view class="popup-header">
          <text class="popup-title">{{ redChargeType === 'inbound' ? '入库红冲' : '出库红冲' }}</text>
          <text class="close-btn" @click="closeRedChargePopup">✕</text>
        </view>
        
        <view class="popup-content">
          <view class="scan-section">
            <view class="scan-area" @click="startScan">
              <text class="scan-icon">📷</text>
              <text class="scan-text">点击扫码</text>
            </view>
          </view>
          
          <view v-if="scannedRecord" class="record-detail">
            <view class="detail-item">
              <text class="label">物料名称：</text>
              <text class="value">{{ scannedRecord.materialName }}</text>
            </view>
            <view class="detail-item">
              <text class="label">规格型号：</text>
              <text class="value">{{ scannedRecord.spec }}</text>
            </view>
            <view class="detail-item">
              <text class="label">数量：</text>
              <text class="value">{{ scannedRecord.quantity }} {{ scannedRecord.unit }}</text>
            </view>
            <view class="detail-item">
              <text class="label">操作时间：</text>
              <text class="value">{{ scannedRecord.operationTime }}</text>
            </view>
            <view class="detail-item">
              <text class="label">操作人：</text>
              <text class="value">{{ scannedRecord.operator }}</text>
            </view>
          </view>
          
          <view v-if="scannedRecord" class="popup-actions">
            <view class="btn btn-cancel" @click="closeRedChargePopup">
              <text>取消</text>
            </view>
            <view class="btn btn-confirm" @click="confirmRedCharge">
              <text>确认红冲</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      timeRange: 'today',
      showDatePicker: false,
      totalInbound: 1250.5,
      totalOutbound: 890.3,
      currentStock: 3650.2,
      inboundTrend: 15.2,
      outboundTrend: -8.5,
      turnoverRate: 3.2,
      topMaterials: [
        { name: '螺纹钢 HRB400', spec: 'Φ12*12000', percentage: 35, color: '#84fab0' },
        { name: '螺纹钢 HRB400', spec: 'Φ16*12000', percentage: 28, color: '#8fd3f4' },
        { name: '盘螺 HRB400', spec: 'Φ8*1000', percentage: 18, color: '#fa709a' },
        { name: '角钢 Q235', spec: '50*50*5', percentage: 12, color: '#fee140' },
        { name: '工字钢 Q235', spec: '20#', percentage: 7, color: '#667eea' }
      ],
      recentRecords: [
        { type: 'inbound', title: '螺纹钢入库', time: '2024-01-15 14:30', amount: 25.5 },
        { type: 'outbound', title: '螺纹钢出库', time: '2024-01-15 10:20', amount: -18.2 },
        { type: 'inbound', title: '盘螺入库', time: '2024-01-15 09:15', amount: 12.8 },
        { type: 'outbound', title: '角钢出库', time: '2024-01-14 16:45', amount: -8.5 }
      ],
      showRedChargePopup: false,
      redChargeType: '',
      scannedRecord: null
    }
  },
  
  onLoad() {
    this.initCharts()
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    changeTimeRange(range) {
      this.timeRange = range
      this.refreshData()
    },
    
    formatNumber(num) {
      return num.toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
    },
    
    getTrendClass(trend) {
      return trend > 0 ? 'trend-up' : 'trend-down'
    },
    
    getStockStatusClass(stock) {
      if (stock < 1000) return 'status-low'
      if (stock > 5000) return 'status-high'
      return 'status-normal'
    },
    
    getStockStatusText(stock) {
      if (stock < 1000) return '偏低'
      if (stock > 5000) return '充足'
      return '正常'
    },
    
    getRecordIconClass(type) {
      return type === 'inbound' ? 'inbound-icon' : 'outbound-icon'
    },
    
    getRecordIcon(type) {
      return type === 'inbound' ? '📥' : '📤'
    },
    
    getAmountClass(amount) {
      return amount > 0 ? 'amount-positive' : 'amount-negative'
    },
    
    initCharts() {
      // 初始化图表数据
      this.drawStockTrendChart()
      this.drawStockDistributionChart()
    },
    
    drawStockTrendChart() {
      // 模拟库存趋势数据
      const ctx = uni.createCanvasContext('stockTrendChart', this)
      const width = 300
      const height = 200
      
      // 绘制坐标轴
      ctx.setStrokeStyle('#e0e0e0')
      ctx.setLineWidth(1)
      ctx.moveTo(40, 20)
      ctx.lineTo(40, 180)
      ctx.lineTo(280, 180)
      ctx.stroke()
      
      // 绘制入库趋势线
      ctx.setStrokeStyle('#84fab0')
      ctx.setLineWidth(2)
      const inboundData = [50, 80, 120, 90, 150, 180, 200]
      for (let i = 0; i < inboundData.length; i++) {
        const x = 40 + (i * 30)
        const y = 180 - (inboundData[i] / 2)
        if (i === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      }
      ctx.stroke()
      
      // 绘制出库趋势线
      ctx.setStrokeStyle('#fa709a')
      ctx.setLineWidth(2)
      const outboundData = [30, 60, 90, 70, 110, 130, 150]
      for (let i = 0; i < outboundData.length; i++) {
        const x = 40 + (i * 30)
        const y = 180 - (outboundData[i] / 2)
        if (i === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      }
      ctx.stroke()
      
      ctx.draw()
    },
    
    drawStockDistributionChart() {
      // 模拟库存分布饼图
      const ctx = uni.createCanvasContext('stockDistributionChart', this)
      const centerX = 150
      const centerY = 100
      const radius = 60
      
      const data = [
        { value: 35, color: '#84fab0' },
        { value: 28, color: '#8fd3f4' },
        { value: 18, color: '#fa709a' },
        { value: 12, color: '#fee140' },
        { value: 7, color: '#667eea' }
      ]
      
      let startAngle = 0
      data.forEach(item => {
        const angle = (item.value / 100) * 2 * Math.PI
        ctx.beginPath()
        ctx.moveTo(centerX, centerY)
        ctx.arc(centerX, centerY, radius, startAngle, startAngle + angle)
        ctx.closePath()
        ctx.setFillStyle(item.color)
        ctx.fill()
        startAngle += angle
      })
      
      ctx.draw()
    },
    
    refreshData() {
      // 模拟数据刷新
      setTimeout(() => {
        uni.showToast({
          title: '数据已更新',
          icon: 'success'
        })
      }, 500)
    },
    
    openInboundRedCharge() {
      this.redChargeType = 'inbound'
      this.showRedChargePopup = true
    },
    
    openOutboundRedCharge() {
      this.redChargeType = 'outbound'
      this.showRedChargePopup = true
    },
    
    closeRedChargePopup() {
      this.showRedChargePopup = false
      this.scannedRecord = null
    },
    
    startScan() {
      uni.scanCode({
        success: (res) => {
          // 模拟扫码结果
          this.scannedRecord = {
            materialName: '螺纹钢 HRB400',
            spec: 'Φ12*12000',
            quantity: 25.5,
            unit: '吨',
            operationTime: '2024-01-15 14:30',
            operator: '张三'
          }
        },
        fail: () => {
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    },
    
    confirmRedCharge() {
      uni.showModal({
        title: '确认红冲',
        content: `确定要红冲${this.redChargeType === 'inbound' ? '入库' : '出库'}记录吗？`,
        success: (res) => {
          if (res.confirm) {
            uni.showToast({
              title: '红冲成功',
              icon: 'success'
            })
            this.closeRedChargePopup()
            this.refreshData()
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.data-insights-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 40rpx;
}

.header-gradient {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 20rpx;
  border-radius: 0 0 40rpx 40rpx;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  font-size: 36rpx;
  color: #fff;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 40rpx;
  font-weight: 700;
  color: #fff;
  margin-right: auto;
  margin-left: 20rpx;
}

.header-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.time-selector {
  padding: 30rpx 30rpx 0;
}

.time-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 24rpx;
  padding: 30rpx;
  backdrop-filter: blur(10px);
}

.time-options {
  display: flex;
  gap: 20rpx;
}

.time-option {
  flex: 1;
  padding: 20rpx;
  text-align: center;
  border-radius: 16rpx;
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  font-size: 26rpx;
  transition: all 0.3s ease;
}

.time-option.active {
  background: rgba(255, 255, 255, 0.3);
  color: #fff;
  font-weight: 600;
}

.metrics-section {
  padding: 30rpx;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.metric-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 20rpx;
  padding: 30rpx;
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.metric-icon {
  font-size: 48rpx;
}

.metric-content {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.metric-value {
  font-size: 36rpx;
  font-weight: 700;
  color: #fff;
  margin-bottom: 5rpx;
}

.metric-label {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 5rpx;
}

.metric-trend, .metric-status {
  font-size: 22rpx;
  font-weight: 600;
}

.trend-up {
  color: #4ade80;
}

.trend-down {
  color: #f87171;
}

.status-low {
  color: #f87171;
}

.status-normal {
  color: #fbbf24;
}

.status-high {
  color: #4ade80;
}

.charts-section {
  padding: 0 30rpx;
}

.chart-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  backdrop-filter: blur(10px);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.chart-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
}

.chart-subtitle {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.chart-legend {
  display: flex;
  gap: 20rpx;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.8);
}

.legend-color {
  width: 16rpx;
  height: 16rpx;
  border-radius: 8rpx;
}

.chart-container {
  height: 300rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-canvas {
  width: 100%;
  height: 100%;
}

.material-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.material-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
}

.material-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.material-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
  margin-bottom: 5rpx;
}

.material-spec {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.material-bar {
  position: relative;
  width: 120rpx;
  height: 8rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.percentage {
  position: absolute;
  top: -20rpx;
  right: 0;
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.8);
}

.red-charge-section {
  padding: 0 30rpx;
  margin-bottom: 30rpx;
}

.operation-records {
  padding: 0 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  margin-bottom: 20rpx;
}

.red-charge-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.red-charge-card {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.red-charge-card:active {
  background: rgba(255, 255, 255, 0.25);
}

.card-icon {
  font-size: 40rpx;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
  margin-bottom: 5rpx;
}

.card-desc {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.card-arrow {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.8);
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.record-item {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  backdrop-filter: blur(10px);
}

.record-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.inbound-icon {
  background: rgba(132, 250, 176, 0.3);
  color: #84fab0;
}

.outbound-icon {
  background: rgba(250, 112, 154, 0.3);
  color: #fa709a;
}

.record-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.record-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #fff;
  margin-bottom: 5rpx;
}

.record-time {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
}

.record-amount {
  font-size: 28rpx;
  font-weight: 600;
}

.amount-positive {
  color: #4ade80;
}

.amount-negative {
  color: #f87171;
}

.red-charge-popup {
  background: #fff;
  border-radius: 40rpx 40rpx 0 0;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  padding: 20rpx;
}

.popup-content {
  padding: 30rpx;
}

.scan-section {
  margin-bottom: 30rpx;
}

.scan-area {
  height: 200rpx;
  background: #f8f9fa;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  cursor: pointer;
}

.scan-icon {
  font-size: 48rpx;
  color: #667eea;
}

.scan-text {
  font-size: 28rpx;
  color: #667eea;
  font-weight: 600;
}

.record-detail {
  margin-bottom: 30rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
}

.btn {
  flex: 1;
  padding: 24rpx;
  border-radius: 50rpx;
  text-align: center;
  font-size: 28rpx;
  font-weight: 600;
}

.btn-cancel {
  background: #f1f5f9;
  color: #64748b;
}

.btn-confirm {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}
</style>